<template>
  <div>
  <el-card class="box-card">
    <el-form :inline="true" :model="studentSearch" class="demo-form-inline">
      <el-form-item label="学生姓名">
        <el-input v-model="studentSearch.sname" placeholder="学生姓名"></el-input>
      </el-form-item>
      <el-form-item label="学生住址">
        <el-input v-model="studentSearch.addr" placeholder="学生住址"></el-input>
      </el-form-item>
      <el-form-item label="所在班级">
        <el-select v-model="studentSearch.cid" placeholder="所在班级">

          <el-option label="所有班级" value="0" ></el-option>
          <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" @click="search"  icon="el-icon-search" >查询</el-button>
      <el-button type="success" @click="add"  icon="el-icon-plus" >添加</el-button>

    </el-form>
    <!--2. 学生列表展示-->
    <el-table
      :data="students"
      style="width: 100%">
      <el-table-column
        label="学号"
        prop="sid"
        align="center"
        width="100">
      </el-table-column>
      <el-table-column
        label="姓名"
        align="center"
        prop="sname"
        width="180"/>
      <el-table-column
        label="性别"
        prop="sex"
        align="center"
        width="180"/>
      <el-table-column
        label="年龄"
        prop="age"
        align="center"
        width="180"/>
      <el-table-column
        label="住址"
        prop="addr"
        align="center"
        width="180"/>
      <el-table-column
        label="所在班级"
        prop="cname"
        align="center"
        width="180"/>
      <el-table-column label="操作" align="center" width="220px">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            size="mini"
            plain
            type="primary"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            icon="el-icon-delete"
            plain
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </el-card>
  <el-dialog :title="title" :visible.sync="dialogFormVisible"  :close-on-click-modal="false">
    {{student}}
    <el-form :model="student" :rules="rules" ref="studForm">
      <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
        <el-input v-model="student.sname" autocomplete="off" placeholder="请输入学生姓名"></el-input>
      </el-form-item>
      <el-form-item label="学生性别" :label-width="formLabelWidth"  prop="sex">
        <!--<el-select v-model="student.sex" placeholder="请选择学生性别" style="width:100%">-->
        <!--    <el-option label="男" value="男"></el-option>-->
        <!--    <el-option label="女" value="女"></el-option>-->
        <!--</el-select>-->
        <el-radio v-model="student.sex" label="男">男</el-radio>
        <el-radio v-model="student.sex" label="女">女</el-radio>
      </el-form-item>
      <el-form-item label="学生年龄" :label-width="formLabelWidth"  prop="age">
        <el-input v-model.number="student.age" autocomplete="off" placeholder="请输入学生年龄"></el-input>
      </el-form-item>
      <el-form-item label="学生住址" :label-width="formLabelWidth"  prop="addr">
        <el-input v-model="student.addr" autocomplete="off" placeholder="请输入学生住址"></el-input>
      </el-form-item>
      <el-form-item label="所在班级" :label-width="formLabelWidth"  prop="cid">
        <el-select v-model="student.cid" placeholder="请选择所在班级"  style="width:100%">
          <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
  import {findAllClasses} from "@/api/classes";
  import {findAllStudents,search,save,delStud} from "@/api/student";

  export default {
        name: "index",
        data(){
          const ageValidator = (rule, value, callback) =>{      //自定义校验证规则
            if(!value){
              callback(new Error('请输入年龄.'));
            }else if(isNaN(value)){
              callback(new Error("年龄必须是数字."))
            }
            callback();
          };
          return {
            studentSearch:{},
            students: [],
            classes:[],
            page:1,
            pageSize:5,
            total:100,
            title:'添加学生',
            dialogFormVisible:false,
            formLabelWidth:"120px",
            student:{},
            rules: {
              sname: [
                {required: true, message: '请输入学生姓名', trigger: 'blur'},
              ],
              sex: [
                { required: true, message: '请选择性别', trigger: 'change' }
              ],
              age: [
                {
                  validator: ageValidator,
                  trigger: 'blur'
                },
              ],
              addr: [
                {required: true, message: '请输入学生住址', trigger: 'blur'},
              ],
              cid: [
                { required: true, message: '请选择所在班级', trigger: 'change' }
              ],
            }
          }
        },
        created() {
          //1. 查询所有班级
          this.findAllClasses()
          //2. 查询所有学生
          //this.findAllStudents()
          //3. 开始条件查询
          this.search();
        },
        methods:{
          //1. 查询 所有班级
          findAllClasses(){
            findAllClasses().then(({data})=>{
              console.log(data);
              this.classes = data.list;
            })
          },
          //2. 查询所有学生
          findAllStudents(){
            findAllStudents().then(({data})=>{
              this.students = data.list;
            })
          },
          //3. 分页带条件查询
          search(){
            search(this.page,this.pageSize,this.studentSearch).then((data)=>{
              console.log("data:",data);
              if(data.code == 20000){
                //3.1 设置总记录数
                this.total = data.data.total;
                //3.2 刷新列表
                this.students = data.data.rows;
              }
            })
          },
          // 添加界面
          add(){
            //1. 修改标题
            this.title = "添加学生"
            //2. 显示对话框
            this.dialogFormVisible = true;
            //3. 清空表单中的数据
            this.student = {}

          },
          //页大小改变时
          handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            console.log(`每页 ${pageSize} 条`);
            this.search();
          },
          //当前页改变
          handleCurrentChange(page) {
            console.log(`当前页: ${page}`);
            this.page = page;
            this.search();
          },
          //保存学生
          save(){
            let _this = this;
            this.$refs['studForm'].validate(valid=>{
              if(valid){
                //1. 根据this.student.sid的值确定是添加还是修改
                let url = "/student/add.do";
                if(this.student.sid){
                  url = "/student/update.do";
                }
                save(url,this.student).then(resp=>{
                  if(resp.code == 20000){
                    this.$message({
                      message: `恭喜你，${this.student.sid?"修改成功！":"添加成功!"}`,
                      type: 'success',
                      onClose(){
                        //1. 刷新页面
                        _this.search();
                        //2. 关闭对话框
                        _this.dialogFormVisible = false;
                      }
                    });
                  }
                })
              }
            })
          },
          //编辑行
          handleEdit(index,row){
            //1. 设置标题
            this.title = "修改学生"
            //2. 显示对话框
            this.dialogFormVisible = true;
            //3. 为当前表单对象student设置值
            this.student = row;
          },
          handleDelete(index,row){
            let _this = this;
            this.$confirm(`真的要删除学生${row.sname}?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {   //代表点击了确定按钮
              delStud(row.sid).then(resp=>{
                  if(resp.code == 20000){
                    this.$message({
                      type: 'success',
                      message: '删除成功!',
                      onClose(){  //消息框关闭时，刷新页面
                        _this.search();
                      }
                    });
                  }
              })


            })

          }
        }
    }
</script>

<style scoped>
  .el-card{
    padding-left:20px;
  }
  .el-pagination{
    margin-top: 20px;
    text-align: right;
  }
</style>
